<template>
  <div class="quotation-audit">
    <div class="filter flex-between flex-align-c layout-content">
      <div class="flex">
        <div class="label tr no-select">分类：</div>
        <div class="content">
          <template v-for="tag in classifyTags">
            <a-checkable-tag
              :key="tag.id"
              :checked="selectedClassifyTags.indexOf(tag.id) > -1"
              @change="
                checked =>
                  categoryChange(tag, checked, 'selectedClassifyTags', 'id')
              "
            >
              <span class="cursor-pointer no-select"
                >{{ tag.categoryName }}
              </span>
            </a-checkable-tag>
          </template>
        </div>
      </div>
      <!-- <c-button type="link" @click="powerSearchVisible = true"
        >高级搜索</c-button
      > -->
    </div>
    <div class="layout-content">
      <c-table
        :data="tableData.pageData"
        :total="tableData.total"
        :columns="columns"
        rowKey="id"
        :loading="loading"
        :expanded="!selectAbled"
        @expanded="getDetail"
        :selection="selectAbled"
        search
        searchPlaceholder="可输入规格、仓库进行搜索"
        @onSearch="onSearch"
        @onSelectChange="onSelectChange"
        @onReload="reload"
      >
        <template v-slot:header-l>
          <template v-if="selectAbled">
            <c-button @click="cancelSelect">取消</c-button>
            <c-button
              type="danger"
              @click="batchReject"
              :disabled="selectedRows.length === 0"
              >拒绝</c-button
            >
            <c-button
              type="success"
              @click="batchAgree"
              :disabled="selectedRows.length === 0"
              >同意</c-button
            >
            <span class="desc" style="padding-left: 12px;"
              >已选 {{ selectedRows.length }} 个报价</span
            >
          </template>
          <c-button type="primary" @click="showBatchExamine" v-else
            >批量审核</c-button
          >
        </template>
        <!-- <template v-slot:header-r>
          <c-search-box placeholder="可输入规格、仓库进行搜索" />
        </template> -->
        <template v-slot:amountAvailableTotalTitle>
          <span>剩余库存 </span>
          <a-tooltip placement="top" :mouseEnterDelay="0.5">
            <template slot="title">
              <span>刷新剩余库存</span>
            </template>
            <a-icon
              type="reload"
              class="cursor-pointer primary"
              @click="getQuotationIds"
              v-if="tableData.pageData && tableData.pageData.length !== 0"
            />
          </a-tooltip>
        </template>
        <template v-slot:amountAvailableTotal="{ row }">
          <span>{{ amountAvailableTotal(row) }}</span>
        </template>
        <template v-slot:expirationDate="{ row }">
          <!-- <c-tags
            :data="[{ label: $getTime(row.expirationDate), color: 'orange' }]"
          ></c-tags> -->
          {{ $getTime(row.expirationDate) }}
        </template>
        <template v-slot:priceType="{ row }">
          <TagsPriceType :flag="row" />
        </template>
        <template v-slot:quotationType="{ row }">
          <TagsStatus :flag="row.quotationType" />
        </template>
        <template v-slot:quotationAuditType="{ row }">
          <TagsAudit :flag="row.quotationAuditType" />
        </template>
        <template v-slot:handle="{ row }">
          <div class="handle">
            <a-dropdown>
              <a-menu slot="overlay">
                <a-menu-item @click="agree(row)">
                  同意
                </a-menu-item>
                <a-menu-item @click="reject(row)">
                  拒绝
                </a-menu-item>
              </a-menu>
              <a-button size="small">操作 <a-icon type="down"/></a-button>
            </a-dropdown>
          </div>
        </template>
        <template slot="expanded" slot-scope="{ row }">
          <QuotationDetail
            type="2"
            :quotationData="quotationData"
            v-if="row.id === quotationData.id"
          />
        </template>
      </c-table>
    </div>
    <c-modal
      v-model="powerSearchVisible"
      title="高级搜索"
      :width="800"
      destroyOnClose
    >
      <Search />
    </c-modal>
  </div>
</template>

<script>
import { mapState } from "vuex";
import quotationDict from "@/dict/quotation";
import Search from "../list/components/search";
import {
  getquotationtoaudit,
  auditQuotation,
  batchauditquotation,
  getamountavailabletotalbyids
} from "@/api/quotation";
import TagsStatus from "@/components-business/quotation/status";
import TagsPriceType from "@/components-business/quotation/priceType";
import TagsAudit from "@/components-business/quotation/audit";
import QuotationDetail from "../components/quotationDetail";

const columns = [
  {
    title: "商品种类",
    dataIndex: "categoryName"
  },
  {
    title: "发布人",
    dataIndex: "createUsername"
  },
  {
    title: "总库存",
    dataIndex: "amountTotal"
  },
  {
    slots: { title: "amountAvailableTotalTitle" },
    scopedSlots: { customRender: "amountAvailableTotal" }
  },
  {
    title: "作价方式",
    scopedSlots: { customRender: "priceType" }
  },
  {
    title: "适用合约月",
    dataIndex: "futuresContract"
  },
  {
    title: "状态",
    scopedSlots: { customRender: "quotationType" }
  },
  {
    title: "审核类型",
    scopedSlots: { customRender: "quotationAuditType" }
  },
  {
    title: "截止时间",
    scopedSlots: { customRender: "expirationDate" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "handle" }
  }
];

export default {
  components: {
    Search,
    TagsStatus,
    TagsPriceType,
    TagsAudit,
    QuotationDetail
  },
  data() {
    return {
      selectAbled: false,
      selectedRows: [],
      selectedClassifyTags: [0],
      quotationDict,
      searchKey: undefined,
      pageNum: 1,
      loading: false,
      tableData: {},
      columns,
      detailData: [],
      detailloading: false,
      powerSearchVisible: false,
      quotationData: {}
    };
  },
  computed: {
    ...mapState(["resource"]),
    // 获取所有分类
    classifyTags() {
      let res = JSON.parse(JSON.stringify(this.resource.categoryRootMenu));
      res.unshift({
        categoryName: "全部",
        id: 0
      });
      return res;
    },
    // 实时计算剩余库存，解决更新table数据后视图没有更新，避免使用$set更新table带来的问题，比如展开行自动收起，因为整个table重新渲染了
    amountAvailableTotal() {
      return row => {
        let res;
        this.tableData.pageData.forEach(item => {
          if (item.id === row.id) res = item.amountAvailableTotal;
        });
        return res;
      };
    }
  },
  methods: {
    // 搜索
    onSearch(val) {
      this.searchKey = val;
      this.reload();
    },
    // 点击刷新剩余库存按钮, 获取所有报价id，用于查询剩余库存
    getQuotationIds() {
      // 没有数据时禁用
      let ids = this.tableData.pageData.map(i => i.id);
      this.getAmountAvailableTotal(ids);
    },
    // 查询剩余库存
    getAmountAvailableTotal(data) {
      this.loading = true;
      getamountavailabletotalbyids({
        quotationIds: data
      })
        .then(res => {
          this.updateAmountAvailableTotal(res);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 更新table剩余库存
    updateAmountAvailableTotal(data) {
      this.tableData.pageData.forEach(item => {
        data.forEach(i => {
          if (item.id === i.id) {
            item.amountAvailableTotal = i.amountAvailableTotal;
          }
        });
      });
    },
    // 刷新
    reload() {
      this.pageNum = 1;
      this.getQuotation();
    },
    // 单个同意
    agree(row) {
      this.examine(1, row);
    },
    // 单个拒绝
    reject(row) {
      this.examine(2, row);
    },
    // 单个审核操作
    examine(type, row) {
      let _this = this;
      // type: 1通过 2拒绝
      this.$confirm({
        title: "温馨提示",
        content:
          type === 1
            ? "是否确认同意该报价审核或上架操作？"
            : "是否确认拒绝该报价审核？",
        onOk() {
          return new Promise(resolve => {
            auditQuotation({
              quotationId: row.id,
              auditState: type,
              version: row.version
            })
              .then(() => {
                _this.$message.success("操作成功");
                _this.reload();
              })
              .finally(() => resolve());
          });
        }
      });
    },
    // 是否批量审批
    showBatchExamine() {
      this.selectAbled = true;
    },
    // 点击复选框时触发
    onSelectChange(selectedRowkeys, selectedRows) {
      this.selectedRows = selectedRows || [];
    },
    // 取消批量操作
    cancelSelect() {
      this.selectAbled = false;
      this.selectedRows = [];
    },
    // 批量审批不通过
    batchReject() {
      this.batchExamine(2);
    },
    // 批量审批通过
    batchAgree() {
      this.batchExamine(1);
    },
    // 批量审核操作
    batchExamine(type) {
      // 格式化参数
      var params = this.selectedRows.map(item => {
        return Object.assign(
          {},
          {
            quotationId: item.id,
            auditState: type,
            version: item.version
          }
        );
      });
      let _this = this;
      // type: 1通过 2拒绝
      this.$confirm({
        title: "温馨提示",
        content:
          type === 1
            ? "是否确认同意所勾选的报价审核或上架？"
            : "是否确认拒绝所勾选的报价审核？",
        onOk() {
          return new Promise(resolve => {
            batchauditquotation(params)
              .then(() => {
                _this.selectAbled = false;
                _this.$message.success("操作成功");
                _this.reload();
              })
              .finally(() => resolve());
          });
        }
      });
    },
    // 设置标签
    setTag(label) {
      return [{ label: label, color: "blue" }];
    },
    categoryChange(tag, checked, selectedTags, val) {
      this[selectedTags] = [tag[val]];
      this.pageNum = 1;
      this.getQuotation();
    },
    // 获取报价详情
    getDetail(data) {
      if (data.expanded) {
        this.quotationData = data.record;
      }
    },
    // 获取待审核报价列表
    getQuotation() {
      this.loading = true;
      getquotationtoaudit({
        searchKey: this.searchKey,
        categoryType:
          this.selectedClassifyTags[0] === 0
            ? undefined
            : this.selectedClassifyTags[0],
        pageData: {
          pageNum: this.pageNum,
          pageSize: 20
        }
      })
        .then(res => {
          this.tableData = res;
        })
        .finally(() => (this.loading = false));
    }
  },
  created() {
    this.getQuotation();
  }
};
</script>

<style lang="scss" scoped>
.filter {
  .label {
    width: 50px;
  }
  .content {
    padding-left: 15px;
  }
  .ant-tag {
    font-size: 14px;
  }
}
</style>
